package com.example.miaoshademo;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Shenluw
 * created：2019/7/17 21:56
 */
@Service
public class MemoryMiaoshaCacheImpl implements MiaoshaCache {
	private final Map<Integer, MiaoshaData> miaoshaDataMap = new ConcurrentHashMap<>(16);

	private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

	private final Lock r = rwl.readLock();
	private final Lock w = rwl.writeLock();

	@Override
	public MiaoshaData get(Integer miaoshaId) {
		r.lock();
		try {
			return miaoshaDataMap.get(miaoshaId);
		} finally {
			r.unlock();
		}
	}

	@Override
	public boolean save(MiaoshaData data) {
		w.lock();
		try {
			MiaoshaData miaoshaData = miaoshaDataMap.get(data.getId());
			if (miaoshaData == null) {
				miaoshaDataMap.put(data.getId(), data);
				return true;
			}
			return false;
		} finally {
			w.unlock();
		}
	}

	@Override
	public boolean update(MiaoshaData data) {
		w.lock();
		try {
			MiaoshaData miaoshaData = miaoshaDataMap.get(data.getId());
			if (miaoshaData == null) {
				return false;
			}
			miaoshaDataMap.put(data.getId(), data);
			return true;
		} finally {
			w.unlock();
		}
	}

	@Override
	public boolean remove(Integer miaoshaId) {
		w.lock();
		try {
			MiaoshaData miaoshaData = miaoshaDataMap.remove(miaoshaId);
			return miaoshaData == null;
		} finally {
			w.unlock();
		}
	}
}
